package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.WeekPlanAppointer;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * Created by wu on 2016/5/4.
 * 周计划
 */
@SuppressWarnings("deprecation") public class WeekPlanFragment extends BaseFragment
    implements View.OnClickListener {

  private static final int REQUEST_FINISHTIME = 0;
  private static final int REQUEST_PLAN_KIND = 1;
  private static final int REQUEST_CHOOSE_CORPORATOR = 2;
  private static final int REQUEST_CHOOSE_APOINTER = 3;
  private static final int REQUEST_ADDFILE = 4;
  private static final int REQUEST_PLAN_PROJECT = 5;
  private String mId;
  private TextView mTv_executor_weekPlan;//执行人
  private TextView mTv_putAppointer_weekPlan;//委派人
  //    private TextView mTv_project_weekPlan;//项目
  private TextView mTv_planClass_workProcess;//计划类别
  private EditText mEt_putPlanContent_addWorkProcess;//计划任务内容
  private TextView mTv_putRequestTime_weekPlan;//要求完成时间
  private TextView mTv_exeDepartment_weekPlan;//执行部门
  private TextView mTv_extraFile_weekPlan;//附件
  private TextView mTv_statusPlan_weekPlan;//数据状态
  private TextView mTv_applicator_weekPlan;//申请人
  private TextView mTv_cooperator_weekPlan;//配合人
  private TextView mTv_register_weekPlan;//登记人
  private TextView mTv_registered_time_weekPlan;//登记时间

  private String mAcquireTime;//要求完成时间
  private String mPlanKindName;//计划类别
  private String mPlanKindCode;//计划类别编码
  private String mApointer;//委派人
  private String mApointerJobNo;//委派人Job
  private String mCorporator;//配合人
  private String mCorporatorJobNo;//配合人job
  private String mFilePath;//附件
  private TextView mTv_planWorkHour_weekPlan;
  //private String mDepartmentName;//部门
  //private String mDepartmentCode;//部门编码
  //private String mWeeksName;//周次
  //    private String mProjectName;//项目名称
  //    private String mProjectId;//项目id

  @Override public void initData() {
    super.initData();
    mId = UUID.randomUUID().toString();
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(R.string.weekPlan);
  }

  /**
   * 获取委派人，默认为部门领导
   */
  private void volleyPostAppointer() {
    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_WEEK_APPOINTER);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        WeekPlanAppointer appointer = new Gson().fromJson(arg0, WeekPlanAppointer.class);
        mApointer = appointer.getName();
        mApointerJobNo = appointer.getJobno();
        mTv_putAppointer_weekPlan.setText(mApointer);
        LogUtil.i("arg0=====" + arg0);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("arg0===" + arg0);
      }
    });
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_add_week_plan, container, false);
    mTv_executor_weekPlan = (TextView) view.findViewById(R.id.tv_executor_weekPlan);
    mTv_putAppointer_weekPlan = (TextView) view.findViewById(R.id.tv_putAppointer_weekPlan);
    //        mTv_project_weekPlan = (TextView) view.findViewById(R.id.tv_project_weekPlan);
    mTv_planClass_workProcess = (TextView) view.findViewById(R.id.tv_planClass_workProcess);
    mTv_putRequestTime_weekPlan = (TextView) view.findViewById(R.id.tv_putRequestTime_weekPlan);
    mEt_putPlanContent_addWorkProcess =
        (EditText) view.findViewById(R.id.tv_putPlanContent_addWorkProcess);
    mTv_exeDepartment_weekPlan = (TextView) view.findViewById(R.id.tv_exeDepartment_weekPlan);
    mTv_extraFile_weekPlan = (TextView) view.findViewById(R.id.tv_extraFile_weekPlan);
    mTv_statusPlan_weekPlan = (TextView) view.findViewById(R.id.tv_statusPlan_weekPlan);
    mTv_cooperator_weekPlan = (TextView) view.findViewById(R.id.tv_cooperator_weekPlan);
    mTv_applicator_weekPlan = (TextView) view.findViewById(R.id.tv_applicator_weekPlan);
    mTv_register_weekPlan = (TextView) view.findViewById(R.id.tv_register_weekPlan);
    mTv_registered_time_weekPlan = (TextView) view.findViewById(R.id.tv_registered_time_weekPlan);
    mTv_planWorkHour_weekPlan = (TextView) view.findViewById(R.id.tv_planWorkHour_weekPlan);
    volleyPostAppointer();
    initDetailData();
    return view;
  }

  private void initDetailData() {
    mTv_executor_weekPlan.setText(mCurrentUser.getRealName());
    mTv_exeDepartment_weekPlan.setText(mCurrentUser.getDeptName());
    mTv_statusPlan_weekPlan.setText(R.string.draft);
    mTv_applicator_weekPlan.setText(mCurrentUser.getRealName());
    mTv_register_weekPlan.setText(mCurrentUser.getRealName());
    mTv_registered_time_weekPlan.setText(MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE));
    mAcquireTime = MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE);
    mTv_putRequestTime_weekPlan.setText(mAcquireTime);

    //        mTv_project_weekPlan.setOnClickListener(this);
    mTv_planClass_workProcess.setOnClickListener(this);
    mTv_putRequestTime_weekPlan.setOnClickListener(this);
    mTv_extraFile_weekPlan.setOnClickListener(this);
    mTv_cooperator_weekPlan.setOnClickListener(this);
    mTv_putAppointer_weekPlan.setOnClickListener(this);
  }

  @Override public void onClick(View v) {

    switch (v.getId()) {
      //            //计划项目
      //            case R.id.tv_project_weekPlan:
      //                Intent proIntent = new Intent(getActivity(), WeekPlanProjectActivity.class);
      //                startActivityForResult(proIntent, REQUEST_PLAN_PROJECT);
      //                break;
      //计划类别
      case R.id.tv_planClass_workProcess:
        showDialog(REQUEST_PLAN_KIND);
        break;
      //要求完成时间
      case R.id.tv_putRequestTime_weekPlan:
        showDialog(REQUEST_FINISHTIME);
        break;
      //附件
      case R.id.tv_extraFile_weekPlan:
        showDialog(REQUEST_ADDFILE);
        break;
      //配合人
      case R.id.tv_cooperator_weekPlan:
        Intent corporIntent = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        corporIntent.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        corporIntent.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, mCorporatorJobNo);
        startActivityForResult(corporIntent, REQUEST_CHOOSE_CORPORATOR);
        break;
      //委派人
      case R.id.tv_putAppointer_weekPlan:

        Intent i = new Intent(getActivity(), SearchPersonActivity.class);
        i.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_APPOINTER);
        startActivityForResult(i, REQUEST_CHOOSE_APOINTER);

        break;
      default:

        break;
    }
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   */
  public void showDialog(int requestCode) {

    DialogFragment dialog = null;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (requestCode) {
      case REQUEST_FINISHTIME:
        dialog = new BaseYMDTimeDialogFragment();
        break;

      case REQUEST_PLAN_KIND:
        Intent intent = new Intent(getActivity(), PlanKindListActivity.class);
        startActivityForResult(intent, requestCode);
        return;
      case REQUEST_ADDFILE:
        dialog = new CompanyForumTopicFileDialogFragment();
        break;

      case REQUEST_PLAN_PROJECT:
        Intent intent1 = new Intent(getActivity(), WeekPlanProjectActivity.class);
        startActivity(intent1);
        break;
      default:
        break;
    }
    if (dialog != null) {
      dialog.setTargetFragment(WeekPlanFragment.this, requestCode);
      dialog.show(fm, "");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    //  要求完成时间
    if (requestCode == REQUEST_FINISHTIME && data != null) {
      Date acquireDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      mAcquireTime = DateUtil.dateToString(acquireDate, DateUtil.TYPE_DATE);
      mTv_putRequestTime_weekPlan.setText(mAcquireTime);

      return;
    }

    //计划类别
    if (requestCode == REQUEST_PLAN_KIND && data != null) {
      CustomerDialog planKind =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      mPlanKindName = planKind.getName();
      mPlanKindCode = planKind.getId();
      mTv_planClass_workProcess.setText(mPlanKindName);
      return;
    }

    //委派人
    if (requestCode == REQUEST_CHOOSE_APOINTER && data != null) {
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      mApointer = dialog.getName();
      mApointerJobNo = dialog.getJobNo();
      // clear代表清空所选 委派人.
      if (mApointerJobNo != null && !mApointerJobNo.equalsIgnoreCase("clear")) {
        mTv_putAppointer_weekPlan.setText(mApointer);
      } else {
        mTv_putAppointer_weekPlan.setText("");
      }
    }

    //配合人
    if (requestCode == REQUEST_CHOOSE_CORPORATOR && data != null) {
      mCorporator = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      mCorporatorJobNo = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      mTv_cooperator_weekPlan.setText(mCorporator);
      return;
    }

    // 添加附件
    if (requestCode == REQUEST_ADDFILE && data != null) {
      mFilePath = data.getStringExtra(CompanyForumTopicFileDialogFragment.EXTRA_RESULT);
      LogUtil.i("mPath=====" + mFilePath);
      if (mFilePath != null) {
        String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath);
        mTv_extraFile_weekPlan.setText(mChoseFileName);
      }
    }

    //        //项目名称
    //        if (requestCode == REQUEST_PLAN_PROJECT && data != null) {
    //            mProjectName = data.getStringExtra(WeekPlanProjectFragment.EXTRA_NAME);
    //            mProjectId = data.getStringExtra(WeekPlanProjectFragment.EXTRA_ITEM);
    //            mTv_project_weekPlan.setText(mProjectName);
    //        }

    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_confirm:
        if (TextUtils.isEmpty(mPlanKindName)) {
          ToastUtil.show(R.string.choosePlanKind);
          return false;
        }
        if (TextUtils.isEmpty(mAcquireTime)) {
          ToastUtil.show(R.string.completeTime);
          return false;
        }
        if (TextUtils.isEmpty(mEt_putPlanContent_addWorkProcess.getText().toString().trim())) {
          ToastUtil.show(R.string.fillPlanDetail);
          return false;
        }

        if (TextUtils.isEmpty(mApointer)) {
          ToastUtil.show(R.string.chooseAppointer);
          return false;
        }
        String planWorkHour = mTv_planWorkHour_weekPlan.getText().toString().trim();
        if (TextUtils.isEmpty(planWorkHour)) {
          ToastUtil.show(R.string.inputPlanWorkHour);
          return false;
        }

        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.cannotEdit);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostSave();
          }
        });

        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();
      default:
        return super.onOptionsItemSelected(item);
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave() {
    String url = ApiConst.URL_WEEK_PLAN;
    RequestParams params = new RequestParams();
    params.put("taskManName", mApointer);
    params.put("taskManId", mApointerJobNo);
    params.put("planEsteTime", mTv_putRequestTime_weekPlan.getText().toString().trim());
    params.put("planKindName", mPlanKindName);
    params.put("planKindCode", mPlanKindCode);
    params.put("planHours", mTv_planWorkHour_weekPlan.getText().toString().trim());
    params.put("planContentDesc", mEt_putPlanContent_addWorkProcess.getText().toString().trim());
    params.put("id", mId);

    if (!TextUtils.isEmpty(mCorporator)) {
      params.put("coopManNames", mCorporator);
      params.put("coopManIds", mCorporatorJobNo);
    }

    //        if (!TextUtils.isEmpty(mProjectName)) {
    //            params.put("projectId", mProjectName);
    //            params.put("projectName", mProjectId);
    //        }

    if (mFilePath != null) {
      InputStream myInputStream = null;
      try {
        myInputStream = new FileInputStream(mFilePath);
      } catch (FileNotFoundException e) {
        LogUtil.e("errorLog==", e);
        ToastUtil.show(R.string.fileNotFound);
      }
      if (myInputStream != null) {
        String name = mFilePath.substring(mFilePath.lastIndexOf("/"), mFilePath.length());
        params.put("myfiles", myInputStream, name);
      }
    }

    MyUtils.showDialogLoading(getActivity(), R.string.loadingSubmit);
    DefaultAsyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
      @Override public void onSuccess(int i, Header[] headers, byte[] bytes) {
        try {
          MyUtils.dismissDialog();
          LogUtil.i("response=", new String(bytes));
          SuccessMessage original = new Gson().fromJson(new String(bytes), SuccessMessage.class);
          String result = original.getResult();
          String isValid = original.getIsValid();
          //成功并有效,使用本地信息,返回上一页面
          if ((MyStringUtil.equals(result, SuccessMessage.SUCCESS)) && (MyStringUtil.equals(isValid,
              SuccessMessage.SUCCESS))) {
            ToastUtil.show(R.string.submit_success);
            mActivity.setResult(Activity.RESULT_OK);
            mActivity.finish();
            //成功,但无效.使用后台信息,弹框,确认后返回上一页面.
          } else if ((MyStringUtil.equals(result, SuccessMessage.SUCCESS)) && (MyStringUtil.equals(
              isValid, SuccessMessage.FAILURE))) {
            mActivity.setResult(Activity.RESULT_OK);
            new AlertDialog.Builder(mActivity).setMessage(original.getMessage())
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                  @Override public void onClick(DialogInterface dialog, int which) {
                    mActivity.finish();
                  }
                })
                .show();
          } else {
            //失败,弹框.
            new AlertDialog.Builder(mActivity).setMessage(original.getMessage())
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                  @Override public void onClick(DialogInterface dialog, int which) {
                  }
                })
                .show();
          }
        } catch (Exception e) {
          e.printStackTrace();
          ToastUtil.show(R.string.submit_failure);
        }
      }

      @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
        ToastUtil.show(R.string.submit_failure);
        LogUtil.e("arg0===" + i);
      }
    });
  }
}
